﻿using Amazon.S3;
using Amazon.S3.Model;
using Microsoft.AspNetCore.Http;
using WMS.Common;
using WMS.Common.Minio;
using WMS.Service.Minio;

public class MinioService : IMinioService
{
    private readonly IAmazonS3 _s3Client;
    private readonly MinioSettings _settings;

    public MinioService(IAmazonS3 s3Client)
    {
        _s3Client = s3Client;
        _settings = AppSettings.GetOptions<MinioSettings>();
    }


    private string GetBucketName(string bucketName = null) => bucketName ?? _settings.DefaultBucket;

    /// <summary>
    /// 检查存储桶是否存在
    /// </summary>
    public async Task<bool> BucketExistsAsync(string bucketName = null)
    {
        var bucket = GetBucketName(bucketName);

        try
        {
            await _s3Client.HeadBucketAsync(new HeadBucketRequest
            {
                BucketName = bucket
            });
            return true;
        }
        catch (AmazonS3Exception ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
        {
            return false;
        }
        catch
        {
            return false;
        }
    }

    public async Task<List<string>> ListBucketsAsync()
    {
        var response = await _s3Client.ListBucketsAsync();
        return response.Buckets.Select(b => b.BucketName).ToList();
    }

    /// <summary>
    /// 创建存储桶
    /// </summary>
    public async Task CreateBucketAsync(string bucketName = null)
    {
        var bucket = GetBucketName(bucketName);

        if (!await BucketExistsAsync(bucket))
        {
            await _s3Client.PutBucketAsync(new PutBucketRequest
            {
                BucketName = bucket
            });
        }
    }

    /// <summary>
    /// 上传文件
    /// </summary>
    public async Task<string> UploadFileAsync(IFormFile file, string bucketName = null)
    {
        var bucket = GetBucketName(bucketName);

        // 确保存储桶存在
        await CreateBucketAsync(bucket);

        var objectName = $"{Guid.NewGuid()}_{file.FileName}";

        using var stream = file.OpenReadStream();
        var request = new PutObjectRequest
        {
            BucketName = bucket,
            Key = objectName,
            InputStream = stream,
            ContentType = file.ContentType
        };

        await _s3Client.PutObjectAsync(request);
        return objectName;
    }

    /// <summary>
    /// 下载文件
    /// </summary>
    public async Task<Stream> DownloadFileAsync(string objectName, string bucketName = null)
    {
        var bucket = GetBucketName(bucketName);

        try
        {
            var request = new GetObjectRequest
            {
                BucketName = bucket,
                Key = objectName
            };

            var response = await _s3Client.GetObjectAsync(request);
            return response.ResponseStream;
        }
        catch (AmazonS3Exception ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
        {
            throw new FileNotFoundException($"文件 {objectName} 不存在", ex);
        }
    }

    /// <summary>
    /// 删除文件
    /// </summary>
    public async Task<bool> DeleteFileAsync(string objectName, string bucketName = null)
    {
        var bucket = GetBucketName(bucketName);

        try
        {
            var request = new DeleteObjectRequest
            {
                BucketName = bucket,
                Key = objectName
            };

            await _s3Client.DeleteObjectAsync(request);
            return true;
        }
        catch (AmazonS3Exception ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
        {
            return false;
        }
    }

    
}